<template>
  <div style="background-color: #f6f6f6; padding: 10px; min-width: 1166px;" class="app-container">
    <el-form class="scheme_query common_shadow" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="76px">
      <el-form-item label=" 方案名称" prop="schemeName">
        <el-input
          v-model="queryParams.schemeName"
          placeholder="请输入方案名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="制作人" prop="schemeProducer">
        <el-input
          v-model="queryParams.schemeProducer"
          placeholder="请输入制作人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="开始时间" prop="startTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.startTime"-->
<!--          type="datetime"-->
<!--          value-format="yyyy-MM-dd HH:mm:ss"-->
<!--          placeholder="选择开始时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="结束时间" prop="endTime">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="queryParams.endTime"-->
<!--                        type="datetime"-->
<!--                        value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                        placeholder="选择结束时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="模板名称" prop="templateName">-->
<!--        <el-input-->
<!--          v-model="queryParams.templateName"-->
<!--          placeholder="请输入模板名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="collect_status_handle common_shadow" key="status_handle_action_key">
      <el-button :loading="startLoading" :disabled="collectingStatus.COLLECTING_STATUS" type="success" @click="startCollect">开始采集</el-button>
      <el-button :loading="endLoading" :disabled="!collectingStatus.COLLECTING_STATUS" style="margin-right: 20px" type="warning" @click="stopCollect">结束采集</el-button>
      <div class="collect_status">
        <label>采集状态：</label>
        <span style="color: green" v-if="collectingStatus.COLLECTING_STATUS == true">采集中</span>
        <span style="color: gray" v-else>未采集</span>
      </div>
      <div class="collect_status">
        <label>入库状态：</label>
        <span style="color: green" v-if="collectingStatus.INSERT_DB_STATUS == true">入库中</span>
        <span style="color: gray" v-else>停止入库</span>
      </div>
      <div class="collect_status" v-if="collectingStatus.COLLECTING_STATUS == true">
        <label>当前正在采集的方案名称：</label>
        <span style="color: green">{{collectingStatus.COLLECTING_SCHEME.schemeName}}</span>
      </div>
    </div>

    <div class="scheme_container">
      <div class="scheme_list_container common_shadow">
        <div class="scheme_item">
          <el-button icon="el-icon-plus" class="scheme_add_btn" type="primary" @click="handleAdd">新增实验方案</el-button>
        </div>
        <template v-if="schemeList.length > 0">
          <div v-for="(item, index) in schemeList"
               :class="'scheme_item' + (index === activeIndex ? ' scheme_item__active' : '')"
               @click="handleSchemeChange(index)">
            <div class="active_block" v-show="index === activeIndex"></div>
            <div class="scheme_info">
              <span>{{item.schemeName}}</span>
              <span>{{item.schemeProducer}}</span>
            </div>
            <div class="scheme_tools">
              <div class="scheme_time">
                <div>{{new Date(item.startTime).toLocaleDateString()}} ~ {{new Date(item.endTime).toLocaleDateString()}}</div>
              </div>
              <div class="tool">
                <i class="el-icon-edit" @click="handleUpdate(item)" style="margin-right: 10px;color: #0CB37C"></i>
                <i class="el-icon-delete" @click="handleDelete(item)" style="color: red"></i>
              </div>
            </div>
            <i class="el-icon-arrow-right active_arrow" v-show="index === activeIndex"></i>
          </div>
        </template>
        <el-empty v-else style="margin-top: 30px" description="暂无数据"></el-empty>
        <pagination
          class="pagination_container"
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <div class="scheme_info_device common_shadow">
        <div class="chart_title_container">
          <div>
            <div class="prev_block"></div>
            <div class="chart_title">查看方案</div>
          </div>
        </div>
        <div style="padding:10px;">
          <el-table
            v-loading="collectItemsLoading"
            size="mini"
            :data="collectItems"
            height="700"
            style="width: 100%;">
            <el-table-column
              prop="name"
              align="center"
              label="采集项">
            </el-table-column>
            <el-table-column
              prop="deviceName"
              align="center"
              label="采集设备">
            </el-table-column>
            <el-table-column
              prop="deviceName"
              align="center"
              label="采集类型">
              <template slot-scope="scope">
                <span>{{Lookup.getLabel(scope.row.type, dict.type.bus_collect_type, 'value', 'label')}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="handleDetailData(scope.row)">数据详情</el-button>
              </template>
            </el-table-column>
<!--            <el-table-column-->
<!--              prop="time"-->
<!--              width="140"-->
<!--              align="center"-->
<!--              label="采集时间">-->
<!--              <template>-->
<!--                2021-11-05 10:10:20-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column-->
<!--              prop="data"-->
<!--              width="60"-->
<!--              align="center"-->
<!--              label="当前值">-->
<!--              <template>-->
<!--                20-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column-->
<!--              prop="data"-->
<!--              width="60"-->
<!--              align="center"-->
<!--              label="修正值">-->
<!--              <template>-->
<!--                3.2-->
<!--              </template>-->
<!--            </el-table-column>-->
          </el-table>
        </div>
      </div>
      <div class="scheme_info_data common_shadow" v-loading="detailLoading">
        <div class="chart_title_container">
          <div>
            <div class="prev_block"></div>
            <div class="chart_title">历史数据记录</div>
          </div>
        </div>
        <ECharts v-show="currentCollectItem && collectDetails.length > 0" ref="dataCharts" class="data_charts_container" :options="options"></ECharts>
        <div v-show="currentCollectItem && collectDetails.length > 0" class="data_detail_container">
          <el-table
            size="mini"
            :data="collectDetails"
            height="500"
            style="width: 100%;margin-right: 10px">
            <el-table-column
              prop="createTime"
              label="时间">
              <template slot-scope="scope">
                {{new Date(scope.row.createTime).toLocaleString()}}
              </template>
            </el-table-column>
            <el-table-column
              prop="actualValue"
              label="数据">
            </el-table-column>
          </el-table>
        </div>
        <div class="no_data_msg" v-show="!(currentCollectItem && collectDetails.length > 0)">
          暂无数据，请点击右侧采集项
        </div>
      </div>
    </div>
<!--    <el-table v-loading="loading" :data="schemeList" @selection-change="handleSelectionChange">-->
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="方案名称" align="center" prop="schemeName" />-->
<!--      <el-table-column label="实验人" align="center" prop="operator" />-->
<!--      <el-table-column label="实验时间" align="center" prop="operateTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模板名称" align="center" prop="templateName" />-->
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['business:scheme:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['business:scheme:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--    </el-table>-->

    <!-- 添加或修改实验方案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body class="input_width200">
      <el-steps :active="activeStep" align-center style="margin-bottom: 30px">
        <el-step title="填写实验信息" icon="el-icon-info"></el-step>
        <el-step title="配置数据采集项" icon="el-icon-upload"></el-step>
        <el-step title="制作完成" icon="el-icon-success"></el-step>
      </el-steps>
      <el-form v-show="activeStep === 0" ref="form" :model="form" :rules="rules" label-width="82px">
        <el-form-item label="方案名称" prop="schemeName">
          <el-input v-model="form.schemeName" placeholder="请输入方案名称" />
        </el-form-item>
        <!--        <el-form-item label="实验人" prop="operator">-->
        <!--          <el-input v-model="form.operator" placeholder="请输入实验人" />-->
        <!--        </el-form-item>-->
        <el-form-item label="制作人" prop="schemeProducer">
          <el-input v-model="form.schemeProducer" placeholder="请输入方案制作人" />
        </el-form-item>
<!--        <el-form-item label="实验时间" prop="operateTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="form.operateTime"-->
<!--                          type="date"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          placeholder="选择实验时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="form.startTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择实验开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="form.endTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择实验结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实验目的" prop="schemePurpose">
          <el-input v-model="form.schemePurpose" type="textarea" :rows="2" placeholder="请输入实验目的" />
        </el-form-item>
        <el-form-item label="实验内容" prop="schemeContent">
          <el-input v-model="form.schemeContent" type="textarea" :rows="4" placeholder="请输入实验内容" />
        </el-form-item>


        <!--        <el-form-item label="模板id" prop="templateId">-->
        <!--          <el-input v-model="form.templateId" placeholder="请输入模板id" />-->
        <!--        </el-form-item>-->
      </el-form>
      <div v-show="activeStep === 1">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleCollectItemsAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="collectItemsSingle"
              @click="handleCollectItemsUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="collectItemsMultiple"
              @click="handleCollectItemsDelete"
            >删除</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="collectItems"
          border
          height="500"
          v-loading="collectItemsLoading"
          @selection-change="handleCollectItemsSelectionChange"
          class="collect_item_table"
          style="width: 100%">
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column
            type="index"
            label="序号">
          </el-table-column>
          <el-table-column
            prop="name"
            label="名称">
          </el-table-column>
          <el-table-column
            prop="type"
            label="采集类型"
            width="110">
            <template slot-scope="scope">
              {{Lookup.getLabel(scope.row.type, dict.type.bus_collect_type, 'value', 'label')}}
            </template>
          </el-table-column>
          <el-table-column
            prop="methodType"
            label="采集方法">
            <template slot-scope="scope">
              {{Lookup.getLabel(scope.row.methodType, dict.type.bus_collect_method, 'value', 'label')}}
            </template>
          </el-table-column>
          <el-table-column
            prop="dimension"
            label="量纲">
          </el-table-column>
          <el-table-column
            prop="acquisitionCardName"
            label="采集卡">
          </el-table-column>
          <el-table-column
            prop="channelName"
            label="通道">
          </el-table-column>
          <el-table-column
            prop="minRange"
            label="量程最小值">
          </el-table-column>
          <el-table-column
            prop="maxRange"
            label="量程最大值">
          </el-table-column>
          <el-table-column
            prop="samplesPerChannel"
            label="每通道采样数">
          </el-table-column>
          <el-table-column
            prop="deviceName"
            label="采集设备">
          </el-table-column>
          <el-table-column
            prop="frequency"
            label="采集频率">
          </el-table-column>
<!--          <el-table-column-->
<!--            prop="startTime"-->
<!--            label="开始时间">-->
<!--          </el-table-column>-->
<!--          <el-table-column-->
<!--            prop="endTime"-->
<!--            label="结束时间">-->
<!--          </el-table-column>-->
        </el-table>
        <div class="message_tip">友情提示：实验信息已上传，点击列表编辑按钮可继续制作方案</div>
      </div>
      <el-result v-show="activeStep === 3" icon="success" title="实验方案制作成功" subTitle="请返回列表页进行查看">
        <template slot="extra">
          <el-button type="primary" size="medium" @click="cancel">返回</el-button>
        </template>
      </el-result>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="activeStep === 0" type="primary" @click="submitForm">下一步</el-button>
        <el-button v-show="activeStep === 1" type="primary" @click="finish">完成</el-button>
        <el-button v-show="activeStep !== 3" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加/修改采集项" :visible.sync="collectItemsOpen" width="700px" append-to-body class="input_width200">
      <el-form inline ref="collectItemsForm" :model="collectItemsForm" :rules="collectItemsRules" label-width="100px">
        <div class="message_tip text_align_right">友情提示：采集卡必须先于通道选择</div>
        <el-form-item label="序号" prop="sortNo">
          <el-input v-model="collectItemsForm.sortNo" placeholder="请输入序号" disabled />
        </el-form-item>
        <el-form-item label="采集项名称" prop="name">
          <el-input v-model="collectItemsForm.name" placeholder="请输入采集项名称" />
        </el-form-item>
        <el-form-item label="采集方法" prop="methodType">
          <el-select v-model="collectItemsForm.methodType" placeholder="请选择采集方法" @change="wen666($event)">
            <el-option
              v-for="dict in dict.type.bus_collect_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <span v-show="ifshow===0">
        <el-form-item label="采集类型" prop="type">
          <el-select v-model="collectItemsForm.type" @change="handleTypeChange" placeholder="请选择采集类型">
            <el-option
              v-for="dict in dict.type.bus_collect_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集卡" prop="acquisitionCardId" :rules="[{required: collectItemsForm.type === '0', message: '请选择采集卡', trigger: 'blur'}]">
          <el-select :disabled="!collectItemsForm.type || collectItemsForm.type === '1'" v-model="collectItemsForm.acquisitionCardId" @change="handleAcquisitionCardChange" placeholder="请选择采集卡">
            <el-option
              v-for="item in acquisitionCards"
              :key="item.acquisitionCardId + 'acquisitionCard'"
              :label="item.name"
              :value="item.acquisitionCardId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通道" prop="channelId">
          <el-select v-if="!collectItemsForm.type || collectItemsForm.type==='0'"
                     :disabled="!collectItemsForm.type || !collectItemsForm.acquisitionCardId"
                     v-model="collectItemsForm.channelId"
                     @change="handleChannelChange"
                     placeholder="请选择通道">
            <el-option
              v-for="(item, index) in channels"
              :key="index + 'channel'"
              :label="item.name"
              :value="item.channelId"
            ></el-option>
          </el-select>
          <el-select v-else-if="!collectItemsForm.type || collectItemsForm.type==='1'" :disabled="!collectItemsForm.type" v-model="collectItemsForm.channelId" placeholder="请选择通道">
            <el-option
              v-for="(item, index) in channels"
              :key="index + 'deviceid'"
              :label="item.channelname"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select @change="handleChannelChange" v-else-if="!collectItemsForm.type || collectItemsForm.type==='2'" :disabled="!collectItemsForm.type" v-model="collectItemsForm.channelId" placeholder="请选择分站">
            <el-option
              v-for="(item, index) in channels"
              :key="index + 'station'"
              :label="item.label"
              :value="item.stationId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集设备" prop="deviceId" :rules="[{required: collectItemsForm.type === '0', message: '请选择采集设备', trigger: 'blur'}]">
          <el-select :disabled="collectItemsForm.type === '1'" v-model="collectItemsForm.deviceId" placeholder="请选择采集设备">
            <el-option
              v-for="item in sensors"
              :key="item.sensorId + 'sensor'"
              :label="item.name"
              :value="item.sensorId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="量纲" prop="dimension" :rules="[{required: collectItemsForm.type === '0', message: '请输入量纲', trigger: 'blur'}]">
          <el-input v-model="collectItemsForm.dimension" placeholder="请输入量纲" />
        </el-form-item>
        <el-form-item label="每秒采样数" prop="samplesPerChannel" :rules="[{required: collectItemsForm.type === '0', message: '请输入每秒采样数', trigger: 'blur'}]">
          <el-input type="number" v-model="collectItemsForm.samplesPerChannel" placeholder="请输入每秒采样数" />
        </el-form-item>
        <el-form-item label="采集频率" prop="frequency" :rules="[{required: collectItemsForm.type === '0', message: '请输入采集频率', trigger: 'blur'}]">
          <el-input v-model="collectItemsForm.frequency" placeholder="请输入采集频率" />
        </el-form-item>
        <el-form-item label="量程最小值" prop="dimension" :rules="[{required: collectItemsForm.type === '0', message: '请输入量程最小值', trigger: 'blur'}]">
          <el-input type="number" v-model="collectItemsForm.minRange" placeholder="请输入量程最小值" />
        </el-form-item>
        <el-form-item label="量程最大值" prop="dimension" :rules="[{required: collectItemsForm.type === '0', message: '请输入量程最大值', trigger: 'blur'}]">
          <el-input type="number" v-model="collectItemsForm.maxRange" placeholder="请输入量程最大值" />
        </el-form-item>
<!--        <el-form-item label="开始时间" prop="startTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="collectItemsForm.startTime"-->
<!--                          type="datetime"-->
<!--                          value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                          placeholder="选择采集开始时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="结束时间" prop="endTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="collectItemsForm.endTime"-->
<!--                          type="datetime"-->
<!--                          value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                          placeholder="选择采集结束时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="采集状态" prop="status">-->
<!--          <el-select v-model="form.status" placeholder="请选择采集状态">-->
<!--            <el-option label="请选择字典生成" value="" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="实验方案id" prop="schemeId">-->
<!--          <el-input v-model="form.schemeId" placeholder="请输入实验方案id" />-->
<!--        </el-form-item>-->
        <el-form-item label="参数" prop="property">
          <el-input class="width200" v-model="collectItemsForm.property" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input class="width200" v-model="collectItemsForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        </span>
        <span v-show="ifshow===1">
          <el-form-item label="采集设备" prop="type">
          <el-select v-model="collectItemsForm.type" @change="handleTypeChange" placeholder="请选择采集类型">
            <el-option
               v-for="item in option"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数值1" prop="dimension" :rules="[{required: collectItemsForm.type === '0', message: '请输入量程最小值', trigger: 'blur'}]">
          <el-input type="number" v-model="value1" placeholder="请输入第一个数值" />
        </el-form-item>
       <el-form-item label="时间" prop="startTime">
          <el-date-picker clearable
                          v-model="time1"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="数值2" prop="dimension" :rules="[{required: collectItemsForm.type === '0', message: '请输入量程最小值', trigger: 'blur'}]">
          <el-input type="number" v-model="value2" placeholder="请输入第二个数值" />
        </el-form-item>
       <el-form-item label="时间" prop="startTime">
          <el-date-picker clearable
                          v-model="time2"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="数值3" prop="dimension" :rules="[{required: collectItemsForm.type === '0', message: '请输入量程最小值', trigger: 'blur'}]">
          <el-input type="number" v-model="value3" placeholder="请输入第三个数值" />
        </el-form-item>
        <el-form-item label="时间" prop="startTime">
          <el-date-picker clearable
                          v-model="time3"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择时间">
          </el-date-picker>
        </el-form-item>
      </span>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="ifshow===1" type="primary" @click="submitCollectItemsForm">数据导入</el-button>
        <el-button v-show="ifshow===1" type="primary" @click="submitCollectItemsForm">模板下载</el-button>  
        <el-button type="primary" @click="submitCollectItemsForm">确 定</el-button>
        <el-button @click="collectItemsCancel">取 消</el-button>
      </div>
      
    </el-dialog>
  </div>
</template>

<script>
import { listScheme, getScheme, delScheme, addScheme, updateScheme, exportScheme, startCollectBySchemeId, stopCollect, getCollectingStatus } from "@/api/business/scheme";
import { listCollection_item, getCollection_item, delCollection_item, addCollection_item, updateCollection_item, exportCollection_item } from "@/api/business/collection_item";
import { listCollected_data, getCollected_data, delCollected_data, addCollected_data, updateCollected_data, exportCollected_data } from "@/api/business/collected_data";

import {debounce, commonGrid, calcFc} from "../../../utils";
import Lookup from "../../../utils/business_data_lookup";


export default {
  name: "Scheme",
  dicts: ['bus_collect_method', 'bus_collect_type'],
  data() {
    return {
      ifshow:0,
      value1:'',
      value2:'',
      value3:'',
      time1:'',
      time2:'',
      time3:'',
      option:[{
          value: '土壤坚实度测定设备',
          label: '土壤坚实度测定设备'
        }, {
          value: '土壤水分测定设备',
          label: '土壤水分测定设备'
        }, {
          value: '土壤容重测定设备',
          label: '土壤容重测定设备'
        }, {
          value: '数据采集器',
          label: '数据采集器'
        }, {
          value: '百分表位移传感器及连线',
          label: '百分表位移传感器及连线'
        }, {
          value: '应变控制式直剪仪',
          label: '应变控制式直剪仪'
        }, {
          value: '全自动应变控制式三轴仪',
          label: '全自动应变控制式三轴仪'
        }],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实验方案表格数据
      schemeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schemeId: null,
        schemeName: null,
        operator: null,
        operateTime: null,
        templateId: null,
        templateName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        schemeName: [
          {
            required: true, message: '请输入实验名称', trigger: 'blur'
          }
        ],
        schemePurpose: [
          {
            required: true, message: '请输入实验目的', trigger: 'blur'
          }
        ],
        schemeContent: [
          {
            required: true, message: '请输入实验内容', trigger: 'blur'
          }
        ],
        schemeProducer: [
          {
            required: true, message: '请输入方案制作人', trigger: 'blur'
          }
        ],

      },
      activeIndex: 0,
      options: {
        grid: commonGrid,
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar',
            barWidth: '20%'
          }
        ]
      },
      // 激活step
      activeStep: 1,
      collectItems: [],
      collectItemsOpen: false,
      collectItemsForm: {},
      collectItemsRules: {
        name: [
          {
            required: true, message: '请输入采集项名称', trigger: 'blur'
          }
        ],
        methodType: [
          {
            required: true, message: '请选择采集方法', trigger: 'blur'
          }
        ],
        type: [
          {
            required: true, message: '请选择采集类型', trigger: 'blur'
          }
        ],
        channelId: [
          {
            required: true, message: '请选择通道', trigger: 'blur'
          }
        ],
      },
      collectItemsIds: [],
      collectItemsSingle: true,
      collectItemsMultiple: true,
      collectItemsLoading: false,
      currentSchemeId: '',
      currentScheme: {},
      Lookup: Lookup,
      acquisitionCards: [],
      sensors: [],
      channels: [],
      collectingStatus: {},
      getCollectingStatusTimer: {},
      getRealTimeDataTimer: {},
      collectDetails: [],
      currentCollectItem: null,
      startLoading: false,
      endLoading: false,
      detailLoading: false,
      stations: [
        {
          stationId: 1,
          label: '分站1',
          cmdCode: 'FF55FFAA010101005188'
        },
        {
          stationId: 2,
          label: '分站2',
          cmdCode: 'FF55FFAA0201010051CC'
        },
        {
          stationId: 3,
          label: '分站3',
          cmdCode: 'FF55FFAA030101005030'
        },
        {
          stationId: 4,
          label: '分站4',
          cmdCode: 'FF55FFAA040101005144'
        },
        {
          stationId: 5,
          label: '分站5',
          cmdCode: 'FF55FFAA050101005100'
        },
      ]
    };
  },
 
  beforeDestroy() {
    this.destroyTimer();
  },
  deactivated() {
    this.destroyTimer();
  },
  activated() {
    this.handleStatusTimer();
  },
  async created() {
    console.log("created", this)
    let data = await this.getList();
    if (data.length > 0) {
      this.currentSchemeId = data[0].schemeId;
      this.currentScheme = data[0];
      this.$nextTick(this.collectItemsGetList);
    }
    this.acquisitionCards = await Lookup.getOptions('ACQUISITION_CARD');
    this.sensors = await Lookup.getOptions('SENSOR');
  },
  methods: {
    /** 查询实验方案列表 */
    getList() {
      this.loading = true;
      return listScheme(this.queryParams).then(response => {
        this.schemeList = response.rows;
        this.total = response.total;
        this.loading = false;
        return response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        schemeId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        schemeName: null,
        operator: null,
        operateTime: null,
        templateId: null,
        templateName: null
      };
      this.collectItems = [];
      this.activeStep = 0;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.schemeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.schemeProducer = this.$store.state.user.name;
      this.activeStep = 0;
      this.open = true;
      this.title = "添加实验方案";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const schemeId = row.schemeId
      getScheme(schemeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改实验方案";
      });
    },
    wen666(e){
      console.log(e)
      if(e==='1'){
      this.ifshow=1
      }else{
        this.ifshow=0
      }
  },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.schemeId != null) {
            updateScheme(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.getList();
              this.activeStep = ++this.activeStep;
              this.currentSchemeId = this.form.schemeId;
              this.$nextTick(this.collectItemsGetList);
            });
          } else {
            addScheme(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.getList();
              this.activeStep = ++this.activeStep;
              this.currentSchemeId = response.data.schemeId;
            });
          }
        }
      });
    },
    finish() {
      this.activeStep = this.activeStep + 2;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const schemeIds = row.schemeId
      this.$confirm('是否确认删除实验方案编号为"' + schemeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delScheme(schemeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有实验方案数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportScheme(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    handleSchemeChange(index) {
      this.activeIndex = index;
      this.currentSchemeId = this.schemeList[index].schemeId;
      this.currentScheme = this.schemeList[index];
      this.$nextTick(this.collectItemsGetList);
    },
    // 取消按钮
    collectItemsCancel() {
      this.collectItemsOpen = false;
      this.collectItemsReset();
    },
    // 表单重置
    collectItemsReset() {
      this.collectItemsForm = {
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        collectionItemId: null,
        sortNo: null,
        dimension: null,
        name: null,
        methodType: null,
        type: null,
        channelId: null,
        deviceId: null,
        property: null,
        frequency: null,
        startTime: null,
        endTime: null,
        status: null,
        schemeId: null
      };
      this.resetForm("collectItemsForm");
    },
    /** 新增采集项按钮操作 */
    handleCollectItemsAdd() {
      this.collectItemsReset();
      this.collectItemsForm.schemeId = this.currentSchemeId;
      this.collectItemsForm.sortNo = ++this.collectItems.length;
      this.collectItemsOpen = true;
    },
    /** 修改采集项按钮操作 */
    handleCollectItemsUpdate(row) {
      const collectItemsIds = row.collectionItemId || this.collectItemsIds
      getCollection_item(collectItemsIds).then(response => {
        this.collectItemsForm = response.data;
        this.collectItemsOpen = true;
      });
    },
    /** 提交采集项按钮 */
    submitCollectItemsForm(index) {
      this.$refs["collectItemsForm"].validate(valid => {
        if (valid) {
          if (this.collectItemsForm.collectionItemId != null) {
            updateCollection_item(this.collectItemsForm).then(response => {
              this.msgSuccess("修改成功");
              this.collectItemsOpen = false;
              this.collectItemsGetList();
            });
          } else {
            addCollection_item(this.collectItemsForm).then(response => {
              this.msgSuccess("新增成功");
              this.collectItemsOpen = false;
              this.collectItemsGetList();
            });
          }
        }
      });
    },
    /** 删除采集项按钮操作 */
    handleCollectItemsDelete(row) {
      const collectItemsIds = row.collectionItemId || this.collectItemsIds;
      this.$confirm('是否确认删除采集项编号为"' + collectItemsIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delCollection_item(collectItemsIds);
      }).then(() => {
        this.collectItemsGetList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleCollectItemsSelectionChange(selection) {
      this.collectItemsIds = selection.map(item => item.collectionItemId)
      this.collectItemsSingle = selection.length!==1
      this.collectItemsMultiple = !selection.length
    },
    collectItemsGetList() {
      this.collectItemsLoading = true;
      this.collectItems = [];
      listCollection_item({schemeId: this.currentSchemeId}).then(response => {
        this.collectItems = response.rows;
        this.collectItemsLoading = false;
      });
    },
    async handleAcquisitionCardChange(val) {
      this.collectItemsForm.cardCode = Lookup.getLabel(val, this.acquisitionCards, 'acquisitionCardId', 'code');
      this.channels = await Lookup.getOptions('CHANNEL', {
        acquisitionCardId: this.collectItemsForm.acquisitionCardId
      })
    },
    async handleChannelChange(val) {
      if (this.collectItemsForm.type === '2') {
        this.collectItemsForm.channelCode = Lookup.getLabel(val, this.stations, 'stationId', 'cmdCode');
        return;
      }
        this.collectItemsForm.channelCode = Lookup.getLabel(val, this.channels, 'channelId', 'code');
    },
    async handleTypeChange(val) {
      this.collectItemsForm.acquisitionCardId = null;
      this.collectItemsForm.channelId = null;
      this.collectItemsForm.cardCode = null;
      this.collectItemsForm.channelCode = null;
      if (val === '1') {
        this.channels = await Lookup.getOptions('VIDEO_CHANNEL')
        return;
      }
      if (val === '0') {
        this.channels = await Lookup.getOptions('CHANNEL', {
          acquisitionCardId: this.collectItemsForm.acquisitionCardId
        });
        return;
      }
      if (val === '2') {
        this.channels = this.stations;
        return;
      }

    },
    async startCollect () {
      if (!this.currentScheme.schemeId) {
        this.$message.error("请选中一个实验方案，再进行采集");
        return;
      }
      try {
        this.startLoading = true;
        let res = await startCollectBySchemeId(this.currentScheme.schemeId);
        if (res.code !== 200) {
          throw new Error(res.msg)
        }
        await this.getCollectingStatus();
        this.$message.success("开始采集...")
      } catch (e) {
        this.$message.error(e)
      } finally {
        this.startLoading = false;
      }
    },
    async stopCollect() {
      try {
        this.endLoading = true;
        let res = await stopCollect();
        if (res.code !== 200) {
          throw new Error()
        }
        await this.getCollectingStatus();
        this.$message.success("停止采集...")
      } catch (e) {
        this.$message.error("停止采集失败")
      } finally {
        this.endLoading = false;
      }
      if (this.getRealTimeDataTimer) {
        window.clearInterval(this.getRealTimeDataTimer);
      }
    },
    async getCollectingStatus() {
      try {
        let res = await getCollectingStatus();
        if (res.code !== 200) {
          throw new Error()
        }
        this.collectingStatus = res.data;
      } catch (e) {
        this.$message.error("获取采集状态失败")
      }
    },
    async loadDetailData(row) {
      let param = {
        collectItemId: row.collectionItemId,
        pageNum: 0,
        pageSize: 500
      }
      try {
        let res = await listCollected_data(param);
        console.log(res);
        if (res.code !== 200) {
          throw new Error();
        }
        let xData = [];
        let yData = [];
        res.rows.reverse();
        res.rows.forEach(item => {
          xData.push(new Date(item.createTime).toLocaleTimeString());
          yData.push(Number(item.actualValue));
        })
        this.options = {
          grid: commonGrid,
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            data: xData
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value} V'
            }
          },
          series: [
            {
              data: yData,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            }
          ]
        }
        this.collectDetails = res.rows;
        this.$nextTick(() => {
          this.$refs['dataCharts'].resize();
        })
      } catch (e) {
        console.log('获取数据异常')
      }
    },
    async handleDetailData(row) {
      this.currentCollectItem = row;
      this.detailLoading = true;
      if (row.type === '2') {
        await this.loadStationData(row)
      } else {
        await this.loadDetailData(row);
      }
      this.$nextTick(() => {
        if (this.getRealTimeDataTimer) {
          window.clearInterval(this.getRealTimeDataTimer);
        }
        if (this.collectingStatus.COLLECTING_STATUS == true) {
          if (row.type === '2') {
            this.getRealTimeDataTimer = setInterval(() => this.loadStationData(row), 1000)
          } else {
            this.getRealTimeDataTimer = setInterval(() => this.loadDetailData(row), 3000)
          }
        }
        this.detailLoading = false;
      })
    },
    destroyTimer() {
      if (this.getCollectingStatusTimer) {
        window.clearInterval(this.getCollectingStatusTimer);
      }
      if (this.getRealTimeDataTimer) {
        window.clearInterval(this.getRealTimeDataTimer);
      }
    },
    async handleStatusTimer() {
      if (this.getCollectingStatusTimer) {
        window.clearInterval(this.getCollectingStatusTimer);
      }
      await this.getCollectingStatus();
      this.getCollectingStatusTimer = setInterval(this.getCollectingStatus, 3000);
    },
    async loadStationData(row) {
      let param = {
        collectItemId: row.collectionItemId,
        pageNum: 0,
        pageSize: 500
      }
      try {
        let res = await listCollected_data(param);
        if (res.code !== 200) {
          throw new Error();
        }
        let xData = [];
        let temp = {
          data1: [],
          data2: [],
          data3: [],
          data4: [],
          data5: [],
          data6: [],
          data7: [],
          data8: [],
        }
        res.rows.reverse();
        res.rows.forEach(item => {
          xData.push(new Date(item.createTime).toLocaleTimeString());
          item.formula.split(",").forEach((subItem, index) => {
            temp['data' + (++index)].push(Number(subItem).toFixed(2));
          })
        })
        this.options = {
          grid: commonGrid,
          legend: {
            data: ['1号', '2号', '3号', '4号', '5号', '6号', '7号', '8号']
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            data: xData
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value} N'
            }
          },
          series: [
            {
              name: '1号',
              data: temp.data1,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
            {
              name: '2号',
              data: temp.data2,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
            {
              name: '3号',
              data: temp.data3,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
            {
              name: '4号',
              data: temp.data4,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
            {
              name: '5号',
              data: temp.data5,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
            {
              name: '6号',
              data: temp.data6,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
            {
              name: '7号',
              data: temp.data7,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
            {
              name: '8号',
              data: temp.data8,
              type: 'line',
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' },
                  { type: 'min', name: '最小值' }
                ]
              },
              markLine: {
                data: [{ type: 'average', name: '均值' }]
              }
            },
          ]
        }
        this.collectDetails = res.rows;
        this.$nextTick(() => {
          this.$refs['dataCharts'].resize();
        })
      } catch (e) {
        console.log(e)
      }
    },

  },
  mounted() {
    window.onresize = debounce(() => {
      this.$refs['dataCharts'].resize();
    })
  },
   
};
</script>
<style lang="scss">
.device_container {
  padding: 0 15px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  max-width: 700px;
  min-height: 200px;
}
.scheme_query {
  background-color: white;
  padding: 0px 4px;
  margin-bottom: 10px;
  .el-form-item {
    margin-top: 10px;
    margin-right: 6px;
    margin-bottom: 10px;
  }
}
.collect_status_handle {
  background-color: white;
  padding: 10px 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  .collect_status {
    margin-right: 20px;
    label {
      font-size: 16px;
    }
    span {
      font-size: 16px;
    }
  }
}
.scheme_container {
  height: calc(100vh - 246px);
  display: flex;
  .scheme_list_container {
    width: 300px;
    height: 100%;
    background-color: white;
    border-radius: 4px;
    overflow: auto;
    position: relative;
    margin-right: 10px;
    .scheme_item {
      border-bottom: 1px solid #D3EAE2;
      color: #999999;
      font-size: 14px;
      font-weight: 600;
      padding: 10px 44px 10px 22px;
      position: relative;
      transition: all .9s;
      &:hover {
        background-color: rgba(249, 255, 253, 1);
        cursor: pointer;
      }
      .active_block {
        background-color: #0CB37C;
        width: 5px;
        position: absolute;
        height: 60px;
        left: 0;
        top: -1px;
      }
      .active_arrow {
        position: absolute;
        right: 10px;
        top: 30px;
        color: #0CB37C;
      }
      .scheme_info {
        display: flex;
        justify-content: space-between;
        span {
          line-height: 16px;
        }
      }
      .scheme_tools {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 6px;
        .scheme_time {
          font-size: 12px;
        }
      }
      .scheme_add_btn {
        width: 230px;
        margin: 4px 12px;
        padding: 10px 10px;
      }
    }
    .scheme_item__active {
      background-color: rgba(249, 255, 253, 1);
    }
    .pagination_container {
      right: 0;
      bottom: 10px;
      position: absolute;
    }
  }
  .scheme_info_device {
    width: 400px;
    height: 100%;
    background-color: white;
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    margin-right: 10px;
  }
  .scheme_info_data {
    width: calc(100% - 710px);
    height: 100%;
    background-color: white;
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    .data_charts_container {
      width: calc(100%);
      //width: 768px;
      height: 300px;
    }
    .data_detail_container {
      display: flex;
      padding: 10px;
    }
  }

}
.message_tip {
  padding: 6px 0;
  color: #0CB37C;
  font-size: 12px;
}
.text_align_right {
  text-align: right;
  position: absolute;
  top: 48px;
  right: 20px;
}
.collect_item_table {
  font-size: 12px !important;
}
.no_data_msg {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #777;
}
</style>
